<?php
/**
 * User：liuJun
 * Date：2022/3/4
 * Time：12:40 PM
 */

namespace Encore\Admin\Console;

use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;

class TableToZwLangCommand extends Command
{
    protected $signature = 'admin:zw {table}';

    protected $description = '生成数据表中文翻译文件';

    public function handle()
    {
        $table = $this->argument('table');
        if (!Schema::hasTable($table)) {
            $this->error("{$table} 表名不存在");

            return;
        }
        $columns = DB::select(/** @lang text */ 'SELECT column_name as col,column_comment as comment FROM information_schema.COLUMNS WHERE table_name = ? AND table_schema = ? order by ordinal_position', [$table, env('DB_DATABASE')]);


        //生成翻译文件名
        $name = Str::of($table)->singular()->snake()->append('.php');
        $dir = resource_path('lang/zh-CN/admin/');

        //创建目录
        if (!is_dir($dir)) {
            (new Filesystem())->makeDirectory($dir, 0755, true);
        }

        $path = $dir.$name;
        $existLang = [];
        if (file_exists($path)) {
            $existLang = include($path);
        }
        foreach ($columns as $column) {
            $col = $column->col;
            $comment = $column->comment ?: Str::of($column->col)->camel()->ucfirst();
            if ('created_at' === $col) {
                $comment = '创建时间';
            }
            if ('updated_at' === $col) {
                $comment = '更新时间';
            }
            if ('deleted_at' === $col) {
                $comment = '删除时间';
            }

            if ('id' === $col && $comment == 'Id') {
                $comment = 'ID';
            }

            if (array_key_exists($col, $existLang)) {
                if (!$existLang[$col]) {
                    $existLang[$col] = $comment;
                }
            } else {
                $existLang[$col] = $comment;
            }

        }
        $str = "<?php\n";
        $str .= "return[\n";
        foreach ($existLang as $column => $comment) {
            $str .= "    '{$column}'=>'{$comment}',\n";
        }
        $str .= "];\n";


        file_put_contents($path, $str);
        $this->info($str);
    }
}